<?php

namespace app\api\controller;

use app\admin\model\Operator;
use app\admin\model\Member;
use app\admin\model\Povertymember;
use app\admin\model\Showpinkunmember;

use think\Request;

/**
 * 精准扶贫首页
 */
class PoveryHomeFrame extends BaseController
{
    /**
     * 首页数据
     */
    public function getPoveryHomeFrame()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }

        $data = [];
        $Townconfig = \app\admin\model\Townconfig::where('townId', $param->townId)->find();
        if(!$Townconfig){
            $data['isshowPovery'] = true;
        }else{
            if($Townconfig->isshowpinkun == 1){
                $data['isshowPovery'] = true;
            }else{
                $Member = Member::where('userId',$param->userId)->find();

                $Showpinkunmember = Showpinkunmember::where('townId',$param->townId)->select();
                if($Showpinkunmember){
                    $memberIdarr = [];
                    foreach ($Showpinkunmember as $v){
                        array_push($memberIdarr,$v['memberId']);
                    }
                    if($Member){
                        if(in_array($Member->id,$memberIdarr)){
                            $data['isshowPovery'] = true;
                        }else{
                            $data['isshowPovery'] = false;
                        }
                    }else{
                        $data['isshowPovery'] = false;
                    }
                }else{
                    $data['isshowPovery'] = true;
                }
            }
        }

        $where = [
            'townId' => $param->townId
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = ['in', ['0', $param->villageId]];
        }

        // 扶贫动态
        $articlePovertydynamic = $this->getArticlePovertydynamic($where);

        // 贫困户
        $povertyMembers = $this->getPovertymembers($where);

        // 扶贫政策
        $articlePolicy = $this->getArticlePolicy($where);

        // 扶贫项目
        $projectWhere = [
            'a.townId' => $param->townId
        ];
        $povertyprojects = action('api/HomeFrame/getPovertyprojects', ['where' => $projectWhere, 'limit' => 10]);

        // 扶贫工作
        $povertyWork = $this->getArticleWork($where);

        $data['articlePovertydynamic'] = $articlePovertydynamic ? : '';
        $data['povertyMembers'] = $povertyMembers ? : '';
        $data['articlePolicy'] = $articlePolicy ? : '';
        $data['povertyprojects'] = $povertyprojects ? : '';
        $data['povertyWork'] = $povertyWork ? : '';

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取扶贫动态
     */
    protected function getArticlePovertydynamic($where)
    {
        //$model = new Article;
        $model = db('article');
        $field = 'id, iconUrl, title, createDate, createOper, readCount, commentCount';
        $result = $model->where($where)->where(['type' => 'povertydynamic'])->field($field)->limit(0, 5)->order('createDate DESC')->select();
        if (!$result) {
            return false;
        }
        foreach ($result as &$item) {
            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['createOper']);
        }

        return $result;
    }

    /**
     * 获取贫困户
     */
    protected function getPovertymembers($where)
    {
        $where['isPoverty'] = 1;
        $model = new Member();
        $field = 'id, name, avatar, villageId';
        $result = $model->where($where)->field($field)->limit(0, 5)->order('sorting ASC,createDate DESC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    /**
     * 获取扶贫政策
     */
    protected function getArticlePolicy($where)
    {
        if(isset($where['villageId'])){
            unset($where['villageId']);
        }

        $area = $this->getParentIdsByTownId($where['townId']);
        $where['xianId'] = $area['xianId'];
        $where['townId'] = ['in', ['0', $where['townId']]];
        //$model = new Article;
        $model = db('article');
        $field = 'id, iconUrl, title, createDate, createOper, readCount, commentCount';
        $result = $model->where($where)->where(['type' => 'policy'])->field($field)->limit(0, 5)->order('createDate DESC')->select();
        if (!$result) {
            return false;
        }
        foreach ($result as &$item) {
            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['createOper']);
        }

        return $result;
    }

    /**
     * 获取扶贫工作
     */
    protected function getArticleWork($where)
    {
        $list =  \app\admin\model\Povertywork::where($where)->where(['isDelete'=>2])->limit(0, 10)->order('createDate DESC')->select();
        foreach ($list as $item) {
            $item['member'] = $item->member1;   // 贫困户基本信息
            $item['memberaid'] = $item->member2;  // 帮扶人信息
            // 扶贫干部 // TODO 不能用 Povertywork 表里的 povertypartyId（扶贫干部）字段，因为贫困户的 aidingId 会发生改变
            $aidingId = Povertymember::where(['memberId' => $item->povertymemberId])->value('aidingId');
            if($aidingId){
                $aidingInfo = Member::where(['id' => $aidingId])->field('id, name, avatar, job')->find();
                $item['memberaid'] = $aidingInfo;
            }

            $item['image'] = $item->image;
            unset($item['member1']);
            unset($item['member2']);
        }

        return $list;
    }

}